package org.example.innovate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.innovate.common.CommonResponse;
import org.example.innovate.domain.*;
import org.example.innovate.domain.Collections;
import org.example.innovate.mapper.*;
import org.example.innovate.service.AliyunSendSmsService;
import org.example.innovate.service.UserService;
import org.example.innovate.util.JwtUtil;
import org.example.innovate.vo.UserAvatarVo;
import org.example.innovate.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.example.innovate.util.OssUpload;

import java.util.*;
import java.util.regex.Pattern;

/**
* @author 马鑫，黄照凌
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-12-29 14:15:48
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Resource
    UserMapper userMapper;
    @Resource
    FollowMapper followMapper;
    @Resource
    MessageMapper messageMapper;
    @Resource
    MyPostMapper myPostMapper;
    @Resource
    PostViewMapper postViewMapper;
    @Resource
    CollectionMapper collectionMapper;
    @Resource
    DishMapper dishMapper;
    @Autowired
    private AliyunSendSmsService aliyunSendSmsService;

    //登录
    @Override
    public CommonResponse<String> login(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", user.getPhone());
        User user1 = userMapper.selectOne(queryWrapper);
        Boolean bool1 = Objects.equals(user.getVcode(),user1.getVcode());
        Boolean bool2 = Objects.equals(user1.getPassword(),user.getPassword());
        if (bool1||bool2)
        {
            String token = JwtUtil.createToken(user1.getPhone(),user1.getPassword());
            return CommonResponse.createForSuccess("登录成功！",token);
        }
        return CommonResponse.createForError("登录失败！");
    }

    //注册
    @Override
    public CommonResponse<User> register(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",user.getPhone());
        User user1 = userMapper.selectOne(queryWrapper);
        String vcode1 = user1.getVcode();
        if (vcode1.equals(user.getVcode())) {
            return CommonResponse.createForSuccess("注册成功！",user1);
        }
        else {
            return CommonResponse.createForError("验证码错误，请输入正确的验证码！");
        }
    }

    @Override
    public CommonResponse<UserVo> updateUser(User user, HttpServletRequest request) {
        String token=request.getHeader("token");
        System.out.println(token);
        JwtUtil.verifyToken(token);
        User user1= JwtUtil.getCurrentUser(token);
        if(user1==null)
        {
            return CommonResponse.createForError("用户不存在");
        }
        user.setUserId(user1.getUserId());
        user.setCreatedAt(user1.getCreatedAt());
        Date time=new Date();
        user.setUpdatedAt(time);
        userMapper.updateById(user);
        String token1;
        UserVo userVo=new UserVo();
        Calendar cal = Calendar.getInstance();
        cal.setTime(user.getCreatedAt());
        cal.add(Calendar.HOUR_OF_DAY, 8);
        Date eightHoursAgo = cal.getTime();
        user.setCreatedAt(eightHoursAgo);
        cal.setTime(user.getUpdatedAt());
        cal.add(Calendar.HOUR_OF_DAY, 8);
        eightHoursAgo = cal.getTime();
        user.setUpdatedAt(eightHoursAgo);
        userVo.setUser(user);
        if(Objects.equals(user1.getPassword(),user.getPassword())&&Objects.equals(user1.getPhone(),user.getPhone()))
        {
            token1=null;
            userVo.setToken(token);
        }
        else {
            token1=JwtUtil.createToken(user.getPhone(),user.getPassword());
            userVo.setToken(token1);
            System.out.println(token1);
        }

        return CommonResponse.createForSuccess("更新成功",userVo);
    }

    @Override
    public CommonResponse<UserVo> getUser(HttpServletRequest request) {
        String token=request.getHeader("token");
        JwtUtil.verifyToken(token);
        User user= JwtUtil.getCurrentUser(token);
        UserVo userVo = new UserVo();
        userVo.setToken(token);
        if(user==null) {
            return CommonResponse.createForError("用户不存在");
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(user.getCreatedAt());
        cal.add(Calendar.HOUR_OF_DAY, 8);
        Date eightHoursAgo = cal.getTime();
        user.setCreatedAt(eightHoursAgo);
        cal.setTime(user.getUpdatedAt());
        cal.add(Calendar.HOUR_OF_DAY, 8);
        eightHoursAgo = cal.getTime();
        user.setUpdatedAt(eightHoursAgo);
        // 用户基本信息
        userVo.setUser(user);
        // 获取关注数、粉丝数、文章数、收藏数、浏览数、信息数
        // 关注数
        QueryWrapper<Follow> followQueryWrapper = new QueryWrapper<>();
        followQueryWrapper.eq("follower_id", user.getUserId());
        userVo.setFollowCount(followMapper.selectCount(followQueryWrapper).intValue());
        // 粉丝数
        followQueryWrapper = new QueryWrapper<>();
        followQueryWrapper.eq("followed_id", user.getUserId());
        userVo.setFollowerCount(followMapper.selectCount(followQueryWrapper).intValue());
        // 浏览历史数
        QueryWrapper<PostView> postViewQueryWrapper = new QueryWrapper<>();
        postViewQueryWrapper.eq("user_id", user.getUserId());
        userVo.setMyPostViewCount(postViewMapper.selectCount(postViewQueryWrapper).intValue());
        // 发布的帖子数
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.eq("user_id", user.getUserId());
        userVo.setMyPostCount(dishMapper.selectCount(dishQueryWrapper).intValue());
        // 收藏数
        QueryWrapper<Collections> collectionQueryWrapper = new QueryWrapper<>();
        collectionQueryWrapper.eq("user_id", user.getUserId());
        userVo.setMyCollectionCount(collectionMapper.selectCount(collectionQueryWrapper).intValue());
        // 信息数
        QueryWrapper<Message> messageQueryWrapper = new QueryWrapper<>();
        messageQueryWrapper.eq("receiver_id", user.getUserId());
        userVo.setMessageCount(messageMapper.selectCount(messageQueryWrapper).intValue());

        return CommonResponse.createForSuccess("查询成功",userVo);
    }

    @Override
    public CommonResponse<UserVo> getUserById(Integer userId) {
        if (userId != null) {
            User user = userMapper.selectById(userId);
            if (user != null) {
                UserVo userVo = new UserVo();
                userVo.setUser(user);
                // 发布的帖子数
                QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
                dishQueryWrapper.eq("user_id", user.getUserId());
                userVo.setMyPostCount(dishMapper.selectCount(dishQueryWrapper).intValue());
                // 关注数
                QueryWrapper<Follow> followQueryWrapper = new QueryWrapper<>();
                followQueryWrapper.eq("follower_id", user.getUserId());
                userVo.setFollowCount(followMapper.selectCount(followQueryWrapper).intValue());
                // 粉丝数
                followQueryWrapper = new QueryWrapper<>();
                followQueryWrapper.eq("followed_id", user.getUserId());
                userVo.setFollowerCount(followMapper.selectCount(followQueryWrapper).intValue());
                return CommonResponse.createForSuccess("查询成功", userVo);
            } else {
                return CommonResponse.createForError("用户不存在");
            }
        }

        return null;
    }

    @Override
    public CommonResponse<UserAvatarVo> upload(MultipartFile image, HttpServletRequest request) {
        String baseurl="food_moment_discover/image/avatar/";
        String token=request.getHeader("token");
        JwtUtil.verifyToken(token);
        User user= JwtUtil.getCurrentUser(token);
        if (user != null) {
            int userId=user.getUserId();
            String dataPath = baseurl +userId+".jpg";
            OssUpload.publishImgToOSS(image,dataPath);
            user.setProfilePicture("https://xiaoxiaobaiyang.oss-cn-shenzhen.aliyuncs.com/food_moment_discover/image/avatar/" +userId+".jpg");
            UserAvatarVo userAvatarVo= new UserAvatarVo();
            userAvatarVo.setProfilePicture(user.getProfilePicture());
            return CommonResponse.createForSuccess("上传成功",userAvatarVo);
        }
        return CommonResponse.createForError("上传失败");
    }
}




